package cn.itsource.org.controller;

import cn.itsource.basic.page.PageList;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*@GetMapping:查询一条 或者 所有
@PostMapping：分页查询
@DeleteMapping 删除
@PutMapping 新增或者修改
@PatchMapping 批量操作
*/

@RestController/*ResponseBody+Controller*/
@RequestMapping("/employee")
@Api(value = "员工的API",description="员工相关的CRUD功能")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    /*查询一条*/
    @GetMapping("/{id}")/*url地址里面写参数占位符 http://localhost:8080/dept/2  */
    @ApiOperation(value = "通过ID查询" )
    public Employee queryOne(@ApiParam(name="ID属性",required = true) @PathVariable("id") Long id){/*@PathVariable 从url路径中取值*/
        return employeeService.queryOne(id);
    }

    /*查询全部*/
    @GetMapping /* http://localhost:8080/dept*/
    public List<Employee> queryAll(){
        return employeeService.queryAll();
    }

    /*分页查询
    @RequestBody作用：到请求体中去取值
    之前：把参数转成 id=5&name=zs 放到请求体中
    现在：把参数转成 json字符串 放到请求体中 这种要取值 就需要@RequestBody这个注解
    * */
    @PostMapping
    public PageList queryPage(@RequestBody EmployeeQuery query){/*参数来自于请求体中 */
        return employeeService.queryPage(query);
    }

    /*删除一个*/
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        /*ctrl + alt + t*/
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMesssage("系统繁忙，请稍后重试");
        }
    }

    /*新增或者修改*/
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if (employee.getId() == null){//添加
                employeeService.add(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMesssage("系统繁忙，请稍后重试");
        }
    }

    /*批量删除*/
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMesssage("操作失败");
        }
    }

}
